import ts from 'typescript';
import { glob } from 'glob';
import _ from 'lodash';
import { log } from '../lib/tools/log';
import { resolverOptions } from '../lib/entity/Options';
import path from 'path';

export function compile(fileList: string[] = [], options: ts.CompilerOptions = {}) {
  let program = ts.createProgram(fileList, options);
  let emitResult = program.emit();
  let diagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
  if (diagnostics.length > 0) {
    diagnostics.forEach(diagnostic => {
      if (diagnostic.file) {
        const {line, character} = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!);
        const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
        log.error(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
      } else {
        log.error(`${ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')}`);
      }
    });
    process.exit(1);
  } else {
    log.info('编译完成。未发现错误。');
  }
}

function resolveTsConfig(tsConfigFilePath: string = './tsconfig.json') {
  // 读取 tsconfig.json 文件
  let tsConfigFile = ts.readConfigFile(tsConfigFilePath, ts.sys.readFile);
  if (tsConfigFile.error) {
    log.error(`tsconfig.json文件读取错误: ${tsConfigFile.error.messageText}`);
    process.exit(1);
  }
  // 解析 tsconfig.json 内容
  return ts.parseJsonConfigFileContent(
      tsConfigFile.config,
      ts.sys,
      path.dirname(tsConfigFilePath),
  );
}

function main() {
  // 初始化参数
  log.init(resolverOptions({}));
  let tsConfig = resolveTsConfig('./tsconfig.json');
  compile(tsConfig.fileNames, tsConfig.options);
}

main();
